<template>
    <div class="detail-container">
        <van-nav-bar
            title="商品详情"
            left-text="返回"
            left-arrow
            @click-left="goBack"
        />
        <!-- 商品图片轮播 -->
        <van-swipe class="detail-swipe" :autoplay="3000" indicator-color="#FF8FA3">
            <van-swipe-item v-for="(img, index) in goodsImgs" :key="index">
                <img :src="img" class="detail-swipe-img"/>
            </van-swipe-item>
        </van-swipe>

        <!-- 商品基本信息 -->
        <div class="goods-info" v-if="currentGoods">
            <h3 class="goods-title">{{ currentGoods.productName }}</h3>
            <div class="goods-price">
                <span class="now-price">¥{{ currentGoods.actualPrice }}</span>
                <span class="old-price" v-if="currentGoods.listPrice">¥{{ currentGoods.listPrice }}</span>
            </div>
            <p class="goods-desc">{{ currentGoods.shortDesc }}</p>
        </div>

        <!-- 商品详情 -->
        <div class="goods-detail" v-if="currentGoods">
            <h4 class="detail-title">商品详情</h4>
            <div class="detail-content" v-html="currentGoods.longDesc"></div>
        </div>

        <!-- 底部操作栏 -->
        <div class="bottom-bar" v-if="currentGoods">
            <van-button class="buy-btn" size="large" color="#E63946" @click="state.showBuy = !state.showBuy">
                立即兑换
            </van-button>
        </div>

        <el-dialog v-model="state.showBuy" title="确认订单" width="100%">
            <el-form label-width="120px">
                <el-form-item label="数量">
                    <!-- 步进器绑定 addForm.num -->
                    <van-stepper v-model="addForm.num" theme="round" button-size="22" />
                </el-form-item>
                <el-form-item>
                    <!-- 金额：数量 × 商品单价（addForm.num * addForm.price） -->
                    <van-submit-bar
                        :price="addForm.num * addForm.price*100"
                        button-text="提交订单"
                        @submit="buyNow"
                    />
                    <van-count-down
                        millisecond
                        :time="countDownTime"
                        format="HH:mm:ss:SS"
                    />
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from "vue-router";
import axios from '@/utils/axios.js';
import { useUserStore } from '@/stores/user'

const us = JSON.parse(sessionStorage.getItem("user"));
const countDownTime = ref(30 * 60 * 1000);
const router = useRouter();
const route = useRoute();

// 存储当前要显示的商品数据
const currentGoods = ref(null);
const goodsImgs = ref([]);
const state = reactive({
    showBuy: false, // 控制弹窗显示隐藏
});

// 订单表单（数量、单价、商品ID等）
const addForm = reactive({
    productId: 0,
    num: 1, // 初始化数量为 1（避免初始为 0）
    address: '',
    price: 0, // 商品单价
});

onMounted(() => {
    // 获取路由传递的商品id
    const productId = route.params.productId;
    console.log("商品id", productId);
    if (productId) {
        // 根据商品id请求商品详情数据
        axios.post(`/api/getGoodById?productId=${productId}`)
            .then(res => {
                console.log("商品赋值执行了", res.data);
                currentGoods.value = res.data;
                // 同步商品ID和单价到表单
                addForm.productId = res.data.productId;
                addForm.price = res.data.actualPrice;
                // 安全处理轮播图（过滤空值和无效链接）
                goodsImgs.value = [
                    res.data.image1,
                    res.data.image2,
                    res.data.image3
                ].filter(img => img && img.trim() !== '');
            })
            .catch(err => {
                console.error("商品详情请求失败", err);
                router.push('/store');
            });
    } else {
        // 没有商品id，跳回首页
        router.push('/store');
        alert('商品不存在');
    }
});

// 返回
const goBack = () => {
    router.back();
};

// 立即兑换（提交订单）
const buyNow = () => {
    axios.post('/api/addOrder', {
        userId: us.userId,
        productId: addForm.productId, // 用表单里的商品ID
        addressId: 1,
        status: '待发货',
        createdAt: Date.now(),
        num: addForm.num, // 传递步进器选择的数量
        price: addForm.num * addForm.price, // 数量 × 单价
    })
        .then(res => {
            console.log("订单添加成功", res.data);
            alert('兑换成功');
            router.push('/store');
        })
        .catch(err => {
            console.error("订单添加失败", err);
        })

};
</script>

<style scoped>
/* 样式部分与原代码一致，无需修改 */
.detail-container {
    background: linear-gradient(to bottom, #FFF9FB, #FFE5EC);
    min-height: 100vh;
    padding-bottom: 60px;
}
.detail-swipe {
    width: 100%;
    height: 300px;
}
.detail-swipe-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.goods-info {
    padding: 15px;
    background-color: #fff;
}
.goods-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 10px;
}
.goods-price {
    display: flex;
    align-items: baseline;
    margin-bottom: 10px;
}
.now-price {
    font-size: 20px;
    color: #E63946;
    font-weight: 600;
    margin-right: 10px;
}
.old-price {
    font-size: 14px;
    color: #999;
    text-decoration: line-through;
}
.goods-desc {
    font-size: 14px;
    color: #666;
    line-height: 1.5;
}
.goods-detail {
    padding: 15px;
    background-color: #fff;
    margin-top: 10px;
}
.detail-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 10px;
}
.detail-content {
    font-size: 14px;
    color: #666;
    line-height: 1.6;
}
.bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    display: flex;
    align-items: center;
    background-color: #fff;
    padding: 10px;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
    justify-content: center;
}
.buy-btn {
    width: 90%;
    border-radius: 25px !important;
}
</style>